package cn.edu.zafu.bigdata.lhff;

import java.io.*;
import java.net.*;

public class UDPClient {
    public static void main(String[] args) {
        DatagramSocket socket = null;
        try {
            String serverAddress = "127.0.0.1";  // 服务端地址
            int serverPort = 9876;  // 服务端端口

            socket = new DatagramSocket();

            // 发送请求到服务端
            String requestMessage = "Get current time";
            DatagramPacket sendPacket = new DatagramPacket(
                    requestMessage.getBytes(),
                    requestMessage.length(),
                    InetAddress.getByName(serverAddress),
                    serverPort
            );
            socket.send(sendPacket);
            System.out.println("Request sent to server for current time.");

            // 接收服务端的响应（即服务器的当前时间）
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String serverTime = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Current time from server: " + serverTime);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}